package com.study.Util;

import com.study.modules.saas.repository.model.ImageDO;
import com.study.modules.saas.service.ImageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Objects;

/**
 * @Author hupengming
 * @ClassName
 * @Date 2022-10-28 14:59
 * @Version 1.0
 */
@Component
public class ImageUtil {

    @Autowired
    private ImageService service;

    private static ImageService imageService;

    @PostConstruct
    public void init() {
        imageService = this.service;
    }

    /**
     * 修改图片正在使用中
     *
     * @param imagePath
     */
    public static void useImage(String imagePath) {
        if (StringUtils.isNotEmpty(imagePath)) {
            ImageDO image = imageService.getImage(imagePath);
            if (Objects.nonNull(image)) {
                image.setStatus(Boolean.TRUE);
                imageService.updateImage(image);
            }
        }
    }

    /**
     * 删除老旧图片，更新新图片
     *
     * @param newImage
     * @param oldImage
     */
    public static void deleteImage(String newImage, String oldImage) {
        if (StringUtils.isAnyEmpty(newImage, oldImage)) {
            ImageDO image = imageService.getImage(oldImage);
            if (Objects.nonNull(image)) {
                imageService.deleteImage(image.getKey());
            }
            useImage(newImage);
        }
    }


}
